﻿
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Mimas.Core.Utility
{
  public static class Toolkit
  {
    public static T CloneStaticItems<T>(T data)
    {
      MemoryStream ms;
      BinaryFormatter bf;

      ms = new MemoryStream();
      bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));

      bf.Serialize(ms, data);
      ms.Seek(0L, SeekOrigin.Begin);

      T result = (T)bf.Deserialize(ms);
      ms.Close();

      return result;
    }

    public static T CloneObject<T>(T objClone) where T : new()
    {
      string GetString = SeralizeObjectToXML<T>(objClone);

      return DeserializeXML<T>(GetString);
    }

    public static T DeserializeXML<T>(string xmlData) where T : new()
    {
      if (string.IsNullOrEmpty(xmlData))
        return default(T);

      TextReader tr = new StringReader(xmlData);
      T DocItms = new T();
      XmlSerializer xms = new XmlSerializer(DocItms.GetType());
      DocItms = (T)xms.Deserialize(tr);

      return DocItms == null ? default(T) : DocItms;
    }

    public static string SeralizeObjectToXML<T>(T xmlObject)
    {
      StringBuilder sbTR = new StringBuilder();
      XmlSerializer xmsTR = new XmlSerializer(xmlObject.GetType());
      XmlWriterSettings xwsTR = new XmlWriterSettings();

      XmlWriter xmwTR = XmlWriter.Create(sbTR, xwsTR);
      xmsTR.Serialize(xmwTR, xmlObject);

      return sbTR.ToString();
    }


  }
}
